package mk.com.ldm.corepoint.implementation.server;

import it.sauronsoftware.cron4j.Scheduler;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;



public class CronScheduler {
	
	private static CronScheduler cronScheduler;
	
	public static CronScheduler getInstance(){
		if(cronScheduler == null) cronScheduler = new CronScheduler();
		return cronScheduler;
	}
	
	protected CronScheduler(){
		
	}
	
	public void clearOldReports(){
		String DATE_FORMAT = "dd-MM-yyyy";
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
		String currentDate = sdf.format(new Date());
		
		
		File reports = new File("../war/reports/");
		
		if(reports.isDirectory()){
			String reportFiles[] = reports.list();
			for(int i =0; i<reportFiles.length; i++){
				File report = new File(reports, reportFiles[i]);
				String dateCreated = new String();
				if(!report.getName().equals(".svn") && report.getName().split("_").length > 1){
					dateCreated = report.getName().split("_")[1];
				}
				
			
				try {
					if(!dateCreated.isEmpty()){
						Date today = sdf.parse(currentDate);
						Date fileDate = sdf.parse(dateCreated);
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(fileDate);
						calendar.add(Calendar.DATE, 2);
						fileDate = calendar.getTime();
						if(today.after(fileDate)){
							report.delete();
						}
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
		
	}
	
	
	public void run(){
		Scheduler s = new Scheduler();
		s.schedule("* * */2 * *", new Runnable(){

			@Override
			public void run() {
				System.out.println("++");
				clearOldReports();				
			}
			
		});
		s.start();
//		// Creates a Scheduler instance.
//		Scheduler s = new Scheduler();
//		// Schedule a once-a-minute task.
//		s.schedule("* * * * *", new Runnable() {
//			public void run() {
//				System.out.println("Another minute ticked away...");
//			}
//		});
//		// Starts the scheduler.
//		s.start();
//		// Will run for ten minutes.
//		try {
//			Thread.sleep(1000L * 60L * 10L);
//		} catch (InterruptedException e) {
//			;
//		}
//		// Stops the scheduler.
//		s.stop();
	}


	
}
